import {findIdsTree, list} from "@/pages/categories/service";
import {getFormOne} from "@/pages/dynamic-form/design-form/service";
import {useRequest} from "@umijs/max";
import {Cascader} from "antd";
import {useRef, useState} from "react";

function findPathByLeafId(categories: any[], targetId: any) {
  // @ts-ignore
  function helper(node: any, path: any[]) {
    // Add current node's id to path
    path.push(node.id);

    // If the current node is the target leaf node, return the path
    // eslint-disable-next-line eqeqeq
    if (node.id == targetId) {
      return path;
    }
    // If the current node has children, recurse into them
    if (node.children) {
      for (let child of node.children) {
        // @ts-ignore
        const result = helper(child, path);
        if (result) {  // If the target was found in this branch
          return result;
        }
      }
    }

    // If not found in this path, remove current node's id and backtrack
    path.pop();
    return null;
  }

  // Initialize the path list and start the recursive search from root nodes
  for (let category of categories) {
    const path = helper(category, []);
    if (path) {
      return path;
    }
  }

  // If the target leaf node is not found, return null or an empty array
  return null;
}

const TypeCascader = (props: any) => {
  const {formId} = props
  const [value, setValue] = useState<any[]>([])
  const [options, setOptions] = useState<any[]>([]);
  const valueRef = useRef<any[]>([]);

  const formatChildren = (data: any[]) => {
    return data.sort((a, b) => a.sort - b.sort).map((item) => {
      const newItem = {
        ...item,
        title: item.name,
        value: item.id,
        label: item.name,
        key: item.id,
      }
      if (newItem.children?.length) {
        newItem.children = formatChildren(newItem.children)
      } else {
        newItem.isLeaf = true
      }
      return newItem
    })
  }

  // 分类名称
  const {run: getTypeNames} = useRequest(async () => {
    const formRes = await getFormOne({
      id: formId,
    });

    if (formRes?.data?.type) {
      // setType(ids?.map((item: any) => parseInt(item)).filter((item: any) => !!item) || [])
      const typeRes = await findIdsTree({
        id: formRes?.data?.type
      })

      // console.log('typeRes', typeRes, options);
      if (typeRes?.data) {
        const newOptions = options.map((item: any) => {
          if (item?.id === typeRes?.data?.id) {
            // eslint-disable-next-line no-param-reassign
            item = {
              ...item,
              title: item.name,
              value: item.id,
              label: item.name,
              key: item.id,
              ...typeRes?.data,
            }

            if (item?.children) {
              item.children = formatChildren(item?.children)
            }
          }
          return item
        })
        const idPath = findPathByLeafId(newOptions, formRes?.data?.type)
        // console.log('idPath', idPath, newOptions)
        setOptions([...newOptions])
        setValue(idPath)
      }
    }
  }, {
    refreshDeps: [formId],
    ready: !!formId && !!options?.length,
  });

  const {loading: cascaderLoading} = useRequest(() => {
    return list({
      level: 1,
      parentId: null
    });
  }, {
    onSuccess(res) {
      const ret = res?.map((item: any) => ({
        ...item,
        title: item.name,
        value: item.id,
        label: item.name,
        key: item.id,
        isLeaf: false,
      }))
      // console.log(ret);
      setOptions([...ret])
      requestIdleCallback(getTypeNames)
    },
  });

  const onChange = (value: (string | number)[], selectedOptions: any[]) => {
    // console.log(value, selectedOptions);
    const targetOption = selectedOptions?.[selectedOptions?.length - 1];
    valueRef.current = value
    // console.log(targetOption)
    // 分类级联只能选中叶子节点
    if (targetOption?.isLeaf) {
      setValue(value)
      props.onChange?.(value, selectedOptions)
    }
  };

  const loadData = async (selectedOptions: any[]) => {
    const targetOption = selectedOptions[selectedOptions.length - 1];

    const {data} = await list({
      parentId: targetOption?.id
    })
    // console.log('data', data)

    if (!data?.length) {
      targetOption.isLeaf = true

      // 分类级联只能选中叶子节点
      if (targetOption?.isLeaf) {
        setValue(valueRef.current)
        props.onChange?.(valueRef.current, selectedOptions)
      }
    }

    targetOption.children = data?.map(item => {
      return {
        ...item,
        title: item.name,
        value: item.id,
        label: item.name,
        key: item.id,
        isLeaf: false
      }
    });
    // console.log('options', options)
    setOptions([...options]);
  };

  return <Cascader
    {...{
      loadData,
      options: options,
      changeOnSelect: true,
      onChange,
      loading: cascaderLoading,
      style: {
        width: '100%'
      },
      value: value,
      onClear() {
        setValue([])
        props.onChange?.([], [])
      }
    }}
    placeholder="请选择类目"
  />
}

export default TypeCascader
